package com.uam.utils;

import cn.hutool.core.util.StrUtil;
import com.uam.common.exception.CustomException;
import com.uam.db.model.entity.User;
import com.uam.db.model.vo.LoginUser;
import com.uam.web.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;

import javax.servlet.http.HttpServletRequest;


public class TokenUtils {

    public static LoginUser getUserForToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            throw new CustomException("非法token");
        }
        // 解析token获取userId
        Long userId;
        String userName;
        String loginName;
        LoginUser loginUser = new LoginUser();
        try {
            Claims claims = JwtUtil.parseToken(token);
            userId = claims.get("userId", Long.class);
            userName = claims.get("userName", String.class);
            loginName = claims.get("loginName", String.class);
            User user = new User();
            user.setUserId(userId);
            user.setUserName(userName);
            user.setLoginName(loginName);
            loginUser.setUser(user);
        } catch (Exception e) {
            throw new CustomException("非法token");
        }
        // 从redis中获取用户信息
        return loginUser;
    }

    public static Long getUserIdForToken(HttpServletRequest request) {
        LoginUser userForToken = getUserForToken(request);
        return userForToken.getUser().getUserId();
    }

    public static String getLoginNameForToken(HttpServletRequest request) {
        LoginUser userForToken = getUserForToken(request);
        return userForToken.getUser().getLoginName();
    }
    public static String getUserNameForToken(HttpServletRequest request) {
        LoginUser userForToken = getUserForToken(request);
        return userForToken.getUser().getUserName();
    }
}
